#!/usr/bin/python
# -*- coding: UTF-8 -*-
import os, shutil, time

datestamp = time.strftime('%Y%m%d', time.localtime(time.time()))
currentPath = os.getcwd()
folderName_date = 'monkeyTest_' + datestamp

def folderPath(fileName = ''):
    if fileName == '':
        path = os.path.join(currentPath, folderName_date, folderName_time)
    else:
        path = os.path.join(currentPath, folderName_date, folderName_time, fileName)
    return path

def dropbox(log_readlines_position = 0):
    dropboxList = []
    dropboxList_all = os.popen('adb shell dumpsys dropbox').readlines()
    for dropboxLog in dropboxList_all:
        if 'system_app_crash' in dropboxLog or 'data_app_crash' in dropboxLog or 'system_app_anr' in dropboxLog or 'data_app_anr' in dropboxLog:
            log_position =  dropboxList_all.index(dropboxLog)
            log = dropboxList_all[log_position] + dropboxList_all[log_position + 1]
            dropboxList.append(log)
    dropCommand_element = dropboxList[-1].replace('\r\n', '').split(' ')
    ymd = dropCommand_element[0]
    hms = dropCommand_element[1]
    processName_position = dropCommand_element.index('Process:') + 1
    processName = dropCommand_element[processName_position].split('/')[0]
    if 'anr' in dropCommand_element[2]:
        errType = 'ANR'
    else:
        errType = 'CRASH'
    getLogCommand = 'adb shell dumpsys dropbox --print %s %s' %(ymd, hms)
    dropbox_logContent_all = os.popen(getLogCommand).readlines()
    log_index = []
    keyword = 'Process: ' + processName
    dropboxLog = ''
    for log_startIndex_line in range(len(dropbox_logContent_all)):
        if keyword in dropbox_logContent_all[log_startIndex_line]:
            log_index.append(log_startIndex_line)
    log_startIndex = max(log_index) + 7
    dropbox_logContent = dropbox_logContent_all[log_startIndex:]
    for log_endIndex_line in range(len(dropbox_logContent)):
        if '===' in dropbox_logContent[log_endIndex_line]:
            log_endIndex = log_endIndex_line
            dropboxLog = ''.join(dropbox_logContent[:log_endIndex])
            break
        else:
            dropboxLog = ''.join(dropbox_logContent)
    return errType, processName, dropboxLog

def bugReport():
    adbVersion = int(os.popen('adb version').readline().split('.')[-1].replace(r'\n', ''))
    if adbVersion > 32:
        os.popen('adb bugreport ' + folderPath())
    else:
        os.popen('adb bugreport > ' + folderPath('bugreport.log'))

def logkit(seed, errType = ''):
    timestamp = time.strftime('%Y%m%d%H%M%S',time.localtime(time.time()))
    global folderName_time
    folderName_time = 'monkeyLog' + timestamp
    os.makedirs(folderPath())
    time.sleep(1)
    os.popen('adb logcat -v time -d > ' + folderPath('logcatReport.log'))
    time.sleep(2)
    logFile_open = open(folderPath('logcatReport.log'))
    logcat_logContent = logFile_open.read()
    logFile_open.close()
    if 'FATAL EXCEPTION:' in logcat_logContent or 'ANR in' in logcat_logContent:
        bugReport()
        errType, processName, dropboxLog = dropbox()
        file_object = open(folderPath('dropboxLog.log'), 'w')
        file_object.writelines(dropboxLog)
        file_object.close()
        if errType == 'ANR':
            os.popen('adb pull /data/anr/traces.txt' + folderPath())
        time.sleep(2)
        folder_rename = os.path.join(currentPath, folderName_date, folderName_time + '_%s_seed%s_%s' %(errType, seed, processName))
        os.rename(folderPath(), folder_rename)
        time.sleep(2)
    else:
        shutil.rmtree(folderPath())
    return errType
